package com.csdj.tcpscoket;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class ServetDemo {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        try {
            //创建服务端的 ServerSocket对象
            ServerSocket serverSocket = new ServerSocket(ClientDemo.PORT);
            Socket socket = serverSocket.accept();
            InputStream is = socket.getInputStream();//获取客户端发送过来的信息
            //套接字节输入流，变成字符缓冲输入流
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            String info =  br.readLine();
            System.out.println(socket.getInetAddress().getHostAddress() +
                            "的客户端发送信息为：" + info);
            //服务端要回复信息给客户端
            //创建字节输出流
            OutputStream os = socket.getOutputStream();
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os));
            System.out.print("请输入回复的信息：");
            String replymsg = input.next();
            bw.write(replymsg); //把信息发送给客户端
            bw.flush();//刷新缓冲区域
            //释放资源
            bw.close();
            os.close();
            br.close();
            is.close();
            socket.close();
            serverSocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
